<template>
	<view class="content">
		<u-navbar :bgColor="bgColor" :fixed="false" title="运营报表" @rightClick="rightClick" :autoBack="true"></u-navbar>

		<view class="container">



			<view class="top row space-between" style="margin-left: 30rpx;">

				<view class="row_a_c" @click="showTime=true">
					<view>开始时间:</view>
					<view class="stime">{{formatDate(start_date)}}</view>
					<image class="xiajian" src="/static/images/xiajian.png"></image>
					<u-datetime-picker @cancel="showTime=false" @confirm="confirmTime()" :show="showTime" v-model="start_date" mode="date" :minuteStep="1"></u-datetime-picker>
				</view>

				<view class="typea row center">
					<view class="wxzz center" :class="{ xxzz: isActive === 'month' }" @click="changeClass('month')">月</view>
					<view class="wxzz center" :class="{ xxzz: isActive === 'week' }" @click="changeClass('week')">周</view>
				</view>

			</view>

			<view class="row_a_c" @click="showTimeEnd=true" style="margin-left: 30rpx;">
				<view>结束时间:</view>
				<view class="stime" v-if="end_date">{{formatDate(end_date)}}</view>
				<view class="stime" v-else>选择结束时间</view>
				<image class="xiajian" src="/static/images/xiajian.png"></image>
				<u-datetime-picker :minDate="1731924800000" @cancel="showTimeEnd=false" @confirm="confirmTimeEnd()" :show="showTimeEnd" v-model="end_date" mode="date" :minuteStep="1"></u-datetime-picker>
			</view>



		</view>


		<view class="chart-con">
			<view class="chart-wrap">
				<view class="title">
					<view class="ver-line"></view>
					<view class="title-desc">经营数据</text></view>
				</view>
				<view class="ring-chart">
					<l-echart ref="barChart"></l-echart>
				</view>
			</view>
		</view>


		<view class="chart-con gap">
			<view class="chart-wrap">
				<view class="title">
					<view class="ver-line"></view>
					<view class="title-desc">预约人次</text></view>
				</view>
				<view class="line-chart-con">
					<l-echart class="line-chart" ref="lineChart"></l-echart>
				</view>
			</view>
		</view>


		<view class="jdtitem">

			<view class="row space-between">
				<view class="row_a_c">
					<view class="nxiang"></view>
					<view class="yyysfb">预约医生</view>
				</view>
			</view>

			<view v-for="(item, index) in orderDoctorData" :key="index">
				<view class="row_a_c space-between bbhh">
					<view class="namet">{{item.doctor.name}}</view>
					<view class="bfbb">{{item.count}}（{{item.ratio}}%）</view>
				</view>
				<u-line-progress :percentage="item.ratio" activeColor="#27CCBB"></u-line-progress>
			</view>


		</view>


		<view class="chart-con" style="margin-top: 30rpx;">
			<view class="chart-wrap">
				<view class="title">
					<view class="ver-line"></view>
					<view class="title-desc">预约科室</view>
				</view>
				<view class="ring-chart">
					<l-echart ref="ringChart"></l-echart>
				</view>
			</view>
		</view>


		<view class="chart-con" style="margin-top: 30rpx;">
			<view class="chart-wrap">
				<view class="title">
					<view class="ver-line"></view>
					<view class="title-desc">预约类型</view>
				</view>
				<view class="ring-chart">
					<l-echart ref="ringChartb"></l-echart>
				</view>
			</view>
		</view>

	</view>

</template>

<script>
	import * as echarts from '@/uni_modules/lime-echart/static/echarts.min.js';
	import LEchart from '@/uni_modules/lime-echart/components/l-echart/l-echart.vue';
	import api_statistics from '@/api/statistics.js';

	export default {
		components: {
			'l-echart': LEchart
		},

		async onShow() {
			this.access_token = uni.getStorageSync('access_token');
			if (!this.access_token) {
				uni.navigateTo({
					url: '/pages/auth/login'
				});
			} else {
				this.start_date = this.getNowDate();
				this.end_date = this.getNowDate();
				this.statisticsConsumeAmountFuc(); // 消费金额统计
				this.statisticsOrderCountFuc(); // 预约人数统计
				this.statisticsOrderDoctorFuc(); // 预约医生统计
				this.statisticsOrderTerritoryFuc(); // 预约科室统计
				this.statisticsOrderTypeFuc(); // 预约类型统计
			}
		},

		data() {
			return {
				isActive: '',
				showTime: false,
				showTimeEnd: false,
				valueTime: null,
				start_date: null,
				end_date: null,

				access_token: null,

				consumeAmountData: [], //消费金额统计
				orderCounttData: [], //预约人数统计
				orderDoctorData: [], //预约医生统计
				orderTerritoryData: [], //预约科室统计
				ordertypeData: [], //预约类型统计

				xfjex: [], //消费金额xxx
				xfjey: [], //消费金额yyy

				yyrsx: [], //预约人数xxx
				yyrsy: [], //预约人数yyy

				kstb: [], //预约科室图表
				lxtb: [], //预约类型统计


				bgColor: 'rgba(0, 31, 63, 0)',
				show: false,
				percentage: 30,
			}
		},

		mounted() {
			this.loadBarData();
			this.loadLineData();
			this.loadRingData();
			this.loadRingDatab();
		},

		methods: {

			// 消费金额统计
			async statisticsConsumeAmountFuc() {
				var per = {
					start_date: this.start_date,
					end_date: this.end_date
				}
				const res = await api_statistics.statisticsConsumeAmount(per);
				if (res.code == 1) {
					this.consumeAmountData = res.data.list;
					this.xfjex = Object.keys(this.consumeAmountData);
					this.xfjex = this.xfjex.map(date => {
						let parts = date.split('-'); // 按照 '-' 分割
						return `${parts[1]}-${parts[2]}`; // 返回 "月-日"
					});
					this.xfjey = Object.values(this.consumeAmountData);
					this.loadBarData();
				} else {
					this.$util.msg(res.message);
					return;
				}
			},


			// 预约人数统计
			async statisticsOrderCountFuc() {
				var per = {
					start_date: this.start_date,
					end_date: this.end_date
				}
				const res = await api_statistics.statisticsOrderCount(per);
				if (res.code == 1) {
					this.orderCounttData = res.data.list;
					this.yyrsx = Object.keys(this.orderCounttData);
					this.yyrsx = this.yyrsx.map(date => {
						let parts = date.split('-'); // 按照 '-' 分割
						return `${parts[1]}-${parts[2]}`; // 返回 "月-日"
					});
					this.yyrsy = Object.values(this.orderCounttData);
					this.loadLineData();
				} else {
					this.$util.msg(res.message);
					return;
				}
			},

			// 预约医生统计
			async statisticsOrderDoctorFuc() {
				var per = {
					start_date: this.start_date,
					end_date: this.end_date
				}
				const res = await api_statistics.statisticsOrderDoctor(per);
				if (res.code == 1) {
					this.orderDoctorData = res.data.list;

					this.loadLineData();
				} else {
					this.$util.msg(res.message);
					return;
				}
			},




			//预约科室统计
			async statisticsOrderTerritoryFuc() {
				var per = {
					start_date: this.start_date,
					end_date: this.end_date
				};
				const res = await api_statistics.statisticsOrderTerritory(per);
				if (res.code == 1) {
					this.orderTerritoryData = res.data.list;
					// 使用 map 方法转换数据
					this.kstb = this.orderTerritoryData.map(item => {
						return {
							value: item.count, // count 转换为 value
							name: item.territory.name // territory.name 转换为 name
						};
					});

					// 调用加载环形图的数据方法
					this.loadRingData(); // 传递 kstb 数据给 loadRingData 方法
				} else {
					this.$util.msg(res.message);
					return;
				}
			},

			//预约类型统计
			async statisticsOrderTypeFuc() {
				var per = {
					start_date: this.start_date,
					end_date: this.end_date
				};
				const res = await api_statistics.statisticsOrderType(per);
				if (res.code == 1) {
					this.ordertypeData = res.data.list;
					// 使用 map 方法转换数据
					this.lxtb = this.ordertypeData.map(item => {
						if (item.type == 1) {
							var mmm = '自己预约'
						} else if (item.type == 2) {
							var mmm = '到店预约'
						} else {
							var mmm = '第三方平台预约'
						}
						return {
							value: item.count, // count 转换为 value
							name: mmm // territory.name 转换为 name
						};
					});

					// 调用加载环形图的数据方法
					this.loadRingDatab(); // 传递 lxtb 数据给 loadRingData 方法
				} else {
					this.$util.msg(res.message);
					return;
				}
			},


			//获取当前时间
			getNowDate() {
				const now = new Date();
				// 格式化日期为 YYYY-MM-DD
				const year = now.getFullYear(); // 获取年份
				const month = String(now.getMonth() + 1).padStart(2, '0'); // 获取月份（0-11），+1 后补零
				const day = String(now.getDate()).padStart(2, '0'); // 获取日期，补零
				const formattedDate = `${year}-${month}-${day}`;
				console.log(formattedDate); // 输出格式为 2024-10-12
				return formattedDate;
			},

			//获取本周开始时间 -结束时间
			getWeekStartAndEnd() {
				const now = new Date();

				// 获取当前日期的星期（0 = Sunday, 1 = Monday, ..., 6 = Saturday）
				const dayOfWeek = now.getDay();

				// 计算本周星期一的日期
				const startOfWeek = new Date(now);
				startOfWeek.setDate(now.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1)); // 调整到星期一

				// 计算本周星期日的日期
				const endOfWeek = new Date(startOfWeek);
				endOfWeek.setDate(startOfWeek.getDate() + 6); // 调整到星期日

				// 格式化为 yyyy-mm-dd
				const formatDate = (date) => date.toISOString().split('T')[0];

				return {
					startDate: formatDate(startOfWeek),
					endDate: formatDate(endOfWeek)
				};
			},




			//获取当月开始时间 -结束时间
			getMonthStartAndEnd() {
				const now = new Date();

				// 获取当前月的开始时间
				const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1); // 当前月的第一天
				const startDate = startOfMonth.toISOString().split('T')[0]; // 格式化为 yyyy-mm-dd

				// 获取当前月的结束时间
				const endOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0); // 下个月的第一天减去一天
				const endDate = endOfMonth.toISOString().split('T')[0]; // 格式化为 yyyy-mm-dd

				return { startDate, endDate };
			},


			confirmTime(e) {
				this.showTime = false;
				this.isActive = '',
					this.statisticsConsumeAmountFuc(); //消费金额统计
				this.statisticsOrderCountFuc(); //预约人数统计
				this.statisticsOrderDoctorFuc(); //预约医生统计
				this.statisticsOrderTerritoryFuc(); //预约科室统计
				this.statisticsOrderTypeFuc(); //预约类型统计

			},

			confirmTimeEnd(e) {
				this.showTimeEnd = false;
				this.isActive = '',
					this.$nextTick(() => {
						console.log('选中的结束时间:', this.end_date);
						this.end_date = this.formatDate(this.end_date);
						this.statisticsConsumeAmountFuc(); //消费金额统计
						this.statisticsOrderCountFuc(); //预约人数统计
						this.statisticsOrderDoctorFuc(); //预约医生统计
						this.statisticsOrderTerritoryFuc(); //预约科室统计
						this.statisticsOrderTypeFuc(); //预约类型统计

					});
			},

			formatDate(value) {
				if (typeof value === 'number') {
					const date = new Date(value); // 时间戳转换为日期对象
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');
					return `${year}-${month}-${day}`;
				}
				return value; // 如果不是时间戳，则直接返回
			},
			changeClass(type) {
				this.isActive = type;
				if (this.isActive == 'month') {
					const { startDate, endDate } = this.getMonthStartAndEnd();
					console.log(`本月开始时间：${startDate}, 本月结束时间：${endDate}`);
					this.start_date = startDate;
					this.end_date = endDate;
					this.statisticsConsumeAmountFuc(); //消费金额统计
					this.statisticsOrderCountFuc(); //预约人数统计
					this.statisticsOrderDoctorFuc(); //预约医生统计
					this.statisticsOrderTerritoryFuc(); //预约科室统计
					this.statisticsOrderTypeFuc(); //预约类型统计
				} else {
					const { startDate, endDate } = this.getWeekStartAndEnd();
					console.log(`本周开始时间：${startDate}, 本周结束时间：${endDate}`);
					this.start_date = startDate;
					this.end_date = endDate;
					this.statisticsConsumeAmountFuc(); //消费金额统计
					this.statisticsOrderCountFuc(); //预约人数统计
					this.statisticsOrderDoctorFuc(); //预约医生统计
					this.statisticsOrderTerritoryFuc(); //预约科室统计
					this.statisticsOrderTypeFuc(); //预约类型统计
				}
			},

			//预约人数统计
			loadLineData() {
				//这里请求服务器拿到数据
				let res = {
					//x轴数据
					xData: this.yyrsx,
					//y轴数据
					yData: this.yyrsy
				}
				//这里option配置参考文档：https://echarts.apache.org/zh/option.html
				let option = {
					xAxis: {
						type: 'category',
						// x轴数据文字颜色
						axisLabel: {
							color: '#a7a7a7'
						},
						// x轴那天坐标轴线的颜色
						axisLine: {
							lineStyle: {
								color: '#f1f1f1',
							}
						},
						//x轴上面刻度线隐藏
						axisTick: {
							show: false,
						},
						//这里是x轴数据
						data: res.xData
					},
					//设置网格
					grid: {
						top: 40,
						bottom: 30,
					},
					//y轴设置
					yAxis: {
						type: 'value',
						//y轴标签文字颜色
						axisLabel: {
							color: '#a7a7a7'
						},
						// y轴分割线设置为虚线
						splitLine: {
							show: true,
							lineStyle: {
								type: 'dashed'
							}
						}
					},
					//设置提示为点击时
					tooltip: {
						trigger: 'axis',
						triggerOn: 'click',
						formatter: '{b} \n 数据: {c}'
					},
					//设置曲线的颜色
					color: ['#27CCBB'],
					series: [{
						//这里是数据
						data: res.yData,
						type: 'line',
						//设置为平滑，默认为折线
						smooth: true,
					}],
					//设置数据缩放，手指缩放
					// dataZoom:{
					// 		type:'inside',//inside移动端就是手指缩放，slider
					// 		id:'123',
					// }
				};
				this.$refs.lineChart.init(echarts, chart => {
					chart.setOption(option);
				});
			},

			loadBarData() {
				//这里请求服务器得到数据
				let myData = {
					x: this.xfjex,
					y: this.xfjey
				}
				//这里option配置参考文档：https://echarts.apache.org/zh/option.html
				this.$refs.barChart.init(echarts, chart => {
					chart.setOption({
						//设置提示为点击时
						tooltip: {
							trigger: 'axis',
							triggerOn: 'click',
							formatter: '{b} \n 数据: {c}'
						},
						//设置曲线的颜色
						color: ['#27CCBB'],
						grid: {
							left: '1%',
							right: '1%',
							bottom: '1%',
							containLabel: true
						},
						yAxis: [{
							type: 'value'
						}],
						xAxis: [{
							type: 'category',
							data: myData.x,
							axisTick: {
								alignWithLabel: true
							}
						}],
						series: [{
							name: '数量',
							type: 'bar',
							barWidth: '40%', //不设时自适应，可以是绝对值例如 40 或者百分数例如 '60%'。百分数基于自动计算出的每一类目的宽度。
							data: myData.y
						}]
					});
				});
			},

			//加载饼环数据,这里可以去请求服务器获取数据
			loadRingData() {
				//这里请求服务器得到数据
				let data = [];

				//这里option配置参考文档：https://echarts.apache.org/zh/option.html
				this.$refs.ringChart.init(echarts, chart => {
					chart.setOption({
						tooltip: {
							trigger: 'item'
						},
						legend: {
							orient: 'vertical', // 设置图例为竖直排列
							top: '5%',
							left: 'right'
						},
						series: [{
							// name: 'Access From',
							type: 'pie',
							radius: ['40%', '70%'],
							avoidLabelOverlap: false,
							label: {
								show: false,
								position: 'center'
							},
							emphasis: {
								label: {
									show: true,
									fontSize: 40,
									fontWeight: 'bold'
								}
							},
							labelLine: {
								show: false
							},
							data: this.kstb
						}]
					});
					//默认突出高亮显示，可以放开下面注释
					// chart.dispatchAction({
					// 	type: 'highlight',
					// 	seriesIndex: 0,
					// 	dataIndex: 0
					// });
					//监听图标项点击事件
					chart.on("click", function(e) {
						for (var i = 0; i < data.length; i++) {
							if (i != e.dataIndex) {
								chart.dispatchAction({
									type: 'downplay', //取消高亮显示;
									seriesIndex: 0,
									dataIndex: i
								});
							} else {
								chart.dispatchAction({
									type: 'highlight', //突出高亮显示;
									seriesIndex: 0,
									dataIndex: i
								});
							}
						}
					});
				});
			},


			loadRingDatab() {
				//这里请求服务器得到数据
				let data = [];

				//这里option配置参考文档：https://echarts.apache.org/zh/option.html
				this.$refs.ringChartb.init(echarts, chart => {
					chart.setOption({
						tooltip: {
							trigger: 'item'
						},
						legend: {
							orient: 'vertical', // 设置图例为竖直排列
							top: '5%',
							left: 'right'
						},
						series: [{
							// name: 'Access From',
							type: 'pie',
							radius: ['40%', '70%'],
							avoidLabelOverlap: false,
							label: {
								show: false,
								position: 'center'
							},
							emphasis: {
								label: {
									show: true,
									fontSize: 40,
									fontWeight: 'bold'
								}
							},
							labelLine: {
								show: false
							},
							data: this.lxtb
						}]
					});
					//默认突出高亮显示，可以放开下面注释
					// chart.dispatchAction({
					// 	type: 'highlight',
					// 	seriesIndex: 0,
					// 	dataIndex: 0
					// });
					//监听图标项点击事件
					chart.on("click", function(e) {
						for (var i = 0; i < data.length; i++) {
							if (i != e.dataIndex) {
								chart.dispatchAction({
									type: 'downplay', //取消高亮显示;
									seriesIndex: 0,
									dataIndex: i
								});
							} else {
								chart.dispatchAction({
									type: 'highlight', //突出高亮显示;
									seriesIndex: 0,
									dataIndex: i
								});
							}
						}
					});
				});
			},

		},
	}
</script>

<style lang="scss" scoped>
	.container {
		margin-bottom: 20rpx;
	}


	::v-deep .u-modal__content {
		padding: 12px 25px 25px 25px;
		display: flex;
		justify-content: normal;

	}

	.stime {
		font-weight: 400;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.85);
		margin-left: 30rpx;
		margin-right: 8rpx;
	}

	.xiajian {
		width: 48rpx;
		height: 48rpx;
	}

	.typea {
		width: 160rpx;
		height: 68rpx;
		margin-right: 15rpx;
	}

	.wxzz {
		width: 60rpx;
		height: 52rpx;
		font-weight: 400;
		font-size: 28rpx;
		color: rgba(0, 0, 0, 0.6);
	}

	.xxzz {
		width: 60rpx;
		height: 52rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.05);
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		font-size: 28rpx;
		color: #27CCBB;
	}







	.content {
		width: 100%;
		min-height: 100vh;
		background-color: #f1f3f2;
		padding: 20rpx 0rpx 100rpx;
	}



	.chart-con {
		width: 100%;
		box-sizing: border-box;
		padding: 0rpx 28rpx;

		.chart-wrap {
			width: 100%;
			box-sizing: border-box;
			background-color: #ffffff;
			padding: 32rpx 0rpx;
			border-radius: 20rpx;

			.title {
				box-sizing: border-box;
				width: 100%;
				padding: 0rpx 28rpx;
				display: flex;
				flex-direction: row;
				justify-content: flex-start;
				align-items: center;
			}

			.ver-line {
				height: 30rpx;
				width: 8rpx;
				border-radius: 10rpx;
				background-color: #4e9d77;
			}

			.title-desc {
				font-size: 30rpx;
				color: #222222;
				margin-left: 22rpx;
				font-weight: bold;
			}

			.ring-chart {
				height: 400rpx;
				width: 100%;
				box-sizing: border-box;
				padding: 0rpx 28rpx;
				margin-top: 32rpx;
			}
		}
	}


	.gap {
		margin-top: 30rpx;
	}


	.jritem {
		width: 695rpx;
		height: 196rpx;
		background: #FFFFFF;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		margin-top: 30rpx;
		margin-left: 30rpx;
		padding: 24rpx 32rpx 32rpx 32rpx;
	}

	.jrxf {
		font-weight: 400;
		font-size: 20rpx;
		color: #7F7F7F;
		margin-bottom: 24rpx;
	}

	.ys {
		font-weight: 400;
		font-size: 24rpx;
		color: rgba(0, 0, 0, 0.85);
	}

	.jjee {
		font-family: PingFangSC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.85);
		margin-top: 5rpx;
	}

	.bycg {
		width: 336rpx;
		height: 192rpx;
		background: #FFFFFF;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		padding: 24rpx 32rpx;
		margin-left: 30rpx;
		margin-top: 30rpx;
	}

	.bycgtitle {
		font-weight: 400;
		font-size: 20rpx;
		color: rgba(0, 0, 0, 0.6);

	}

	.ccgg {
		width: 720rpx;
	}

	.bymetl {
		font-weight: 500;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.85);
		margin-top: 12rpx;
		margin-bottom: 12rpx;
	}

	.bfbb {
		font-weight: 400;
		font-size: 24rpx;
		color: #EA4140;
	}

	.jsy {
		font-weight: 400;
		font-size: 24rpx;
		color: rgba(0, 0, 0, 0.6);
	}

	.jdtitem {
		width: 690rpx;
		height: 620rpx;
		background: #FFFFFF;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		margin-left: 30rpx;
		margin-top: 30rpx;
		padding: 38rpx 24rpx;
	}

	.nxiang {
		width: 8rpx;
		height: 32rpx;
		background: linear-gradient(180deg, #EBF6F6 0%, #27CCBB 100%);
		border-radius: 8rpx 8rpx 8rpx 8rpx;
		margin-right: 16rpx;
	}

	.yyysfb {
		font-weight: 800;
		font-size: 32rpx;
		color: rgba(0, 0, 0, 0.85);
	}

	.zzyyaa {
		width: 152rpx;
		height: 64rpx;
		background: #FAFAFA;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		padding: 10rpx;
	}

	.yyymm {
		width: 56rpx;
		height: 48rpx;
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		font-weight: 400;
		font-size: 24rpx;
		margin-right: 10rpx;
	}

	.zzzmm {
		width: 56rpx;
		height: 48rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 20rpx 0rpx rgba(0, 0, 0, 0.05);
		border-radius: 12rpx 12rpx 12rpx 12rpx;
		font-weight: 400;
		font-size: 24rpx;
		color: #27CCBB;
	}

	.bbhh {
		margin-top: 40rpx;
		margin-bottom: 20rpx;
	}

	.namet {
		font-weight: 400;
		font-size: 28rpx;
		color: rgba(0, 0, 0, 0.85);
	}

	.bfbb {
		font-weight: 400;
		font-size: 24rpx;
		color: rgba(0, 0, 0, 0.6);
	}
</style>